package com.thiswhyme.demo.msgpush.core;

import cn.hutool.json.JSONUtil;
import com.thiswhyme.common.expection.BusinessException;
import com.thiswhyme.demo.msgpush.core.event.bean.WebSocketEvent;
import com.thiswhyme.demo.msgpush.core.event.EventHandler;
import com.thiswhyme.demo.msgpush.core.event.bean.EventType;
import com.thiswhyme.redis.subscribe.AbstractRedisSubscriber;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @description: WebSocket事件redis广播订阅者
 * @author: thiswhyme
 * @date: 2021/9/28
 */
@Slf4j
@AllArgsConstructor
@Component
public class WebSocketEventRedisSubscriber extends AbstractRedisSubscriber {

    private final Map<String, EventHandler> eventHandlerMap;

    @Override
    public String getChannelName() {
        return WsConstant.WS_MSG_PUSH_CHANNEL;
    }

    @Override
    public void doBizOperation(Message message, byte[] pattern) {
        WebSocketEvent event = JSONUtil.toBean(new String(message.getBody()), WebSocketEvent.class);
        if (null == event || null == event.getEventType()) {
            throw new BusinessException("消息内容不完整");
        }
        getEventHandler(event.getEventType()).handle(event);
    }

    /**
     * 获取WebSocket事件处理器
     * @param eventType
     * @return
     */
    private EventHandler getEventHandler(EventType eventType) {
        EventHandler result = null;
        for (EventHandler handler : eventHandlerMap.values()) {
            if (eventType.equals(handler.supportType())) {
                result = handler;
            }
        }
        return Optional.ofNullable(result).orElseThrow(() -> new BusinessException("事件处理器不存在"));
    }
}
